package com.runvp.controller;

import com.runvp.common.constant.ConstantRedisKey;
import com.runvp.common.core.domain.AjaxResult;
import com.runvp.common.core.redis.RedisCache;
import com.runvp.common.enums.NettyCmd;
import com.runvp.common.exception.base.BaseException;
import com.runvp.common.utils.StringUtils;
import com.runvp.handler.SendInsideCmdHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@Controller
@ResponseBody
@RequestMapping("/app/cmd")
public class CmdController {


    @Autowired
    private SendInsideCmdHandler sendInsideCmdHandler;
    @Autowired
    private RedisCache redisCache;



    /**
     *  指令执行
     */
    @GetMapping("/{type}/{cmd}")
    public AjaxResult cmd(@PathVariable("type") String type,@PathVariable("cmd") String cmd, String sn, String param, String outCode) {
        log.info("本次执行命令【type:{},cmd:{},sn:{},param:{},outCode:{}】",type,cmd,sn,param,outCode);
        String redisKey = ConstantRedisKey.AUTH_OUT+sn;
        String authCode = redisCache.getCacheObject(redisKey);
        if(StringUtils.isBlank(authCode) || StringUtils.isBlank(outCode)){
            throw new BaseException("授权码为空或无效");
        }
        if (!authCode.equals(outCode)) {
            throw new BaseException("授权码无效");
        }
        redisCache.deleteObject(redisKey);
        return AjaxResult.success(sendInsideCmdHandler.send(NettyCmd.build(type,cmd),sn,param));
    }


}
